package com.subaiqiao.yunshiyuan.config.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Token鉴权配置
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    /**
     * 白名单
     */
    private String urls[] = {
            "/ysy/user-info/Login.do",
            "/ysy/user-info/RootLogin.do",
            "/ysy/user-info/ViefLogin.do",
            "/ysy/user-info/InsertUser.do",
            "/ysy/user-info/ChangePasswordByPhone.do",
            "/ysy/product/FindProductPage.do",
            "/ysy/product/FindProductDetails.do"
    };

    /**
     * TODO 此处要换成Redis
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
//    @Autowired
//    private UserInfoService userInfoService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean result = false;
        String url = request.getRequestURI();
        String token = request.getHeader("Authorization");
        for (String item : this.urls) {
            if (item.equals(url)) {
                result = true;
                break;
            }
        }
        if (!result) {
//            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
//            wrapper.eq("token", token);
//            UserInfo user = userInfoService.getOne(wrapper);
//        if (user==null){
            if (false) {
               response.setCharacterEncoding("UTF-8");
               response.setContentType("application/json;charset=utf-8");
               PrintWriter out = null;
               try{
                   response.setContentType("application/json");
                   JSONObject jsonObject = new JSONObject();
                   jsonObject.put("code",500);
                   jsonObject.put("msg","您的登录过期");
                   String res = jsonObject.toJSONString();
                   out = response.getWriter();
                   out.append(res);
                   out.flush();
                    return false;
               }catch (Exception e){
                   e.printStackTrace();
                   response.sendError(500);
                   return false;
               }
            }
            result = true;
        }
        return result;
    }
}
